﻿using B.S.BasicData.Api.Read.Application.Command.RoleMenu;
using B.S.BasicData.Domian.Entities.Menu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.RoleMenu
{
    public class RoleMenuCreateHandler : IRequestHandler<RoleMenuCreateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleMenuModel> rolemenuRepo;

        public RoleMenuCreateHandler(IBaseRepository<RoleMenuModel> rolemenuRepo)
        {
            this.rolemenuRepo = rolemenuRepo;
        }
        public Task<ApiResult<int>> Handle(RoleMenuCreateCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<int>();
            List<int>menuid=request.Menuid.Split(',').Select(x=>Convert.ToInt32(x)).ToList();
            foreach (var item in menuid)
            {
                var role = rolemenuRepo.GetAll().FirstOrDefault(x => x.Rid == request.RoleId);
                if (role != null)
                {
                    rolemenuRepo.Delete(role);
                }
            }
            foreach (var item in menuid)
            {
                RoleMenuModel role = new RoleMenuModel()
                {
                       Rid= request.RoleId,
                       Mid= item
                };
                rolemenuRepo.Add(role);
            }
            res.Message = "添加成功";
            res.Code=ApiEnum.Ok;
           
           return Task.FromResult(res);
        }
    }
}
